/**
 * 
 */
package com.alibaba.hello.validate;

import org.springmodules.validation.valang.functions.AbstractFunction;
import org.springmodules.validation.valang.functions.Function;

/**
 * @author sesame.yangj
 * 
 */
public class BytesSizeFunction extends AbstractFunction {

	private String defaultEncoding = "utf-8";

	public BytesSizeFunction(Function[] arguments, int line, int column) {
		super(arguments, line, column);
	}

	protected Object doGetResult(Object target) throws Exception {
		if (getArguments() == null || getArguments().length == 0) {
			throw new IllegalArgumentException("the arguments is empty.");
		}
		// 参数大于1
		if (getArguments().length > 1) {
			Object value = getArguments()[0].getResult(target);
			if (value == null)
				return 0;
			String encoding = getArguments()[1].getResult(target).toString();
			return value.toString().getBytes(encoding).length;
		} else {
			Object value = getArguments()[0].getResult(target);
			if (value == null)
				return 0;
			else {
				return value.toString().getBytes(defaultEncoding).length;
			}
		}
	}

}
